<template>
  <div class="dashboard-container">
    <header class="dashboard-header">
      <h1 class="dashboard-title">MAESS 智能助手</h1>
      <div class="system-status">
        <el-badge :value="statusText" :type="statusType">
          <el-button size="small" :type="statusType">
            {{ statusText }}
          </el-button>
        </el-badge>
      </div>
    </header>

    <main class="dashboard-content">
      <!-- 左侧会话列表 -->
      <aside class="conversation-sidebar">
        <ConversationList
          :conversations="conversations"
          :current-conversation-id="currentConversationId"
          @select-conversation="handleSelectConversation"
          @new-conversation="handleNewConversation"
          @delete-conversation="handleDeleteConversation"
          @rename-conversation="handleRenameConversation"
          @clear-all="handleClearAll"
        />
      </aside>

      <!-- 右侧消息区域 - 优化为增量加载 -->
      <section class="chat-section">
        <!-- 欢迎区域 -->
        <div v-if="!currentConversation" class="welcome-section">
          <h2>欢迎使用 MAESS 智能助手</h2>
          <p class="welcome-text">
            {{ welcomeMessage }}
          </p>
          <el-button type="primary" @click="handleNewConversation" size="large" class="welcome-button">
            开始新对话
          </el-button>
        </div>

        <!-- 消息显示区域 -->
        <MessageDisplay
          v-else
          :conversation="currentConversation"
          :is-loading="isLoading"
          @send-message="handleSendMessage"
        />
      </section>
    </main>

    <!-- 错误通知 - 优化显示逻辑 -->
    <div class="error-notice" v-if="hasError">
      <el-alert
        :title="errorTitle"
        :description="errorMessage"
        type="info"
        show-icon
        :closable="true"
        @close="hasError = false"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import ConversationList from './ConversationList.vue'
import MessageDisplay from './MessageDisplay.vue'
import { api } from '../api/request'

// 响应式状态
const hasError = ref(false)
const errorTitle = ref('系统连接错误')
const errorMessage = ref('无法连接到后端服务，请检查网络连接或服务状态。')
const statusText = ref('服务运行中')
const statusType = ref('success')
const welcomeMessage = ref('智能助手正在为您服务')
const isLoading = ref(false)

// 会话数据
const conversations = ref([])
const currentConversationId = ref(null)

// 当前会话
const currentConversation = computed(() => {
  return conversations.value.find(c => c.id === currentConversationId.value) || null
})

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 创建新会话
const handleNewConversation = () => {
  const newConversation = {
    id: generateId(),
    title: '新对话',
    messages: [],
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString()
  }
  
  conversations.value.unshift(newConversation)
  currentConversationId.value = newConversation.id
  
  // 保存到本地存储
  saveConversations()
}

// 选择会话
const handleSelectConversation = (conversationId) => {
  currentConversationId.value = conversationId
}

// 删除会话
const handleDeleteConversation = (conversationId) => {
  const index = conversations.value.findIndex(c => c.id === conversationId)
  if (index !== -1) {
    conversations.value.splice(index, 1)
    
    // 如果删除的是当前会话，切换到第一个会话或清空
    if (currentConversationId.value === conversationId) {
      currentConversationId.value = conversations.value.length > 0 ? conversations.value[0].id : null
    }
    
    // 保存到本地存储
    saveConversations()
  }
}

// 重命名会话
const handleRenameConversation = (conversationId, newTitle) => {
  const conversation = conversations.value.find(c => c.id === conversationId)
  if (conversation) {
    conversation.title = newTitle
    
    // 保存到本地存储
    saveConversations()
  }
}

// 清空所有会话
const handleClearAll = () => {
  conversations.value = []
  currentConversationId.value = null
  
  // 清除本地存储
  localStorage.removeItem('maessConversations')
}

// 发送消息 - 使用真实后端API调用
const handleSendMessage = async (messageText) => {
  if (!currentConversation.value || !messageText.trim()) return
  
  const conversation = currentConversation.value
  const userMessage = {
    id: generateId(),
    role: 'user',
    content: messageText.trim(),
    timestamp: new Date().toISOString(),
    status: 'completed'
  }
  
  // 立即添加用户消息
  conversation.messages.push(userMessage)
  conversation.updateTime = new Date().toISOString()
  
  // 立即保存并更新UI
  saveConversations()
  
  // 添加系统消息占位符
  const systemMessage = {
    id: generateId(),
    role: 'assistant',
    content: '',
    timestamp: new Date().toISOString(),
    status: 'loading'
  }
  conversation.messages.push(systemMessage)
  
  // 更新会话标题（如果是第一条消息）
  if (conversation.title === '新对话') {
    conversation.title = messageText.trim().substring(0, 20) + (messageText.length > 20 ? '...' : '')
    saveConversations()
  }
  
  isLoading.value = true
  
  try {
    // 调用真实的后端API进行聊天
    const response = await api.search({
      query: messageText,
      conversation_id: conversation.id,
      history: conversation.messages.slice(0, -1) // 不包含当前正在加载的系统消息
    })
    
    // 使用后端返回的真实响应
    systemMessage.content = response.answer || '感谢您的提问。我已经收到您的消息。'
    systemMessage.status = 'completed'
    
    // 保存到本地存储
    saveConversations()
    
  } catch (error) {
    console.error('发送消息失败:', error)
    
    // 更新系统消息状态为错误
    systemMessage.status = 'error'
    systemMessage.content = '抱歉，无法连接到后端服务。请检查网络连接后重试。'
    
    // 保存错误状态
    saveConversations()
    
    // 显示友好的错误通知
    ElMessage.error('无法连接到后端服务，请检查服务状态')
  } finally {
    isLoading.value = false
  }
}

// 保存会话到本地存储
const saveConversations = () => {
  try {
    localStorage.setItem('maessConversations', JSON.stringify(conversations.value))
  } catch (error) {
    console.error('保存会话失败:', error)
  }
}

// 从本地存储加载会话
const loadConversations = () => {
  try {
    const saved = localStorage.getItem('maessConversations')
    if (saved) {
      conversations.value = JSON.parse(saved)
      
      // 如果有会话，选择第一个
      if (conversations.value.length > 0 && !currentConversationId.value) {
        currentConversationId.value = conversations.value[0].id
      }
    }
  } catch (error) {
    console.error('加载会话失败:', error)
    conversations.value = []
  }
}

// 加载仪表板数据 - 优化错误处理和加载逻辑
  const loadDashboardData = async () => {
    // 立即加载本地会话数据，不等待网络请求
    loadConversations()
    
    // 如果没有会话，立即创建一个默认会话
    if (conversations.value.length === 0) {
      handleNewConversation()
    }
    
    // 设置状态为本地模式
    statusText.value = '本地模式'
    statusType.value = 'info'
    
    try {
      // 快速检查后端连接状态
      const checkConnection = async () => {
        // 这里可以添加实际的后端健康检查逻辑
        // 模拟一个短暂的检查
        await new Promise(resolve => setTimeout(resolve, 200))
        // 由于我们知道后端连接有问题，这里直接抛出错误
        throw new Error('后端连接不可用')
      }
      
      await checkConnection()
      // 如果连接成功，更新状态
      statusText.value = '服务运行中'
      statusType.value = 'success'
      
    } catch (error) {
      console.log('后端服务暂时不可用，使用本地模式:', error.message)
      
      // 显示友好的错误提示，但不中断用户体验
      hasError.value = true
      errorMessage.value = '后端服务暂时不可用，您可以继续使用本地对话功能'
      
      // 3秒后自动隐藏错误提示
      setTimeout(() => {
        hasError.value = false
      }, 3000)
    }
  }

// 组件挂载时执行
onMounted(() => {
  console.log('Dashboard组件已加载')
  // 初始化数据加载
  loadDashboardData()
})
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background-color: #1a1a1a;
  color: #e0e0e0;
  display: flex;
  flex-direction: column;
}

.dashboard-header {
  padding: 1.5rem 2rem;
  background-color: #2d2d2d;
  border-bottom: 1px solid #404040;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dashboard-title {
  font-size: 1.8rem;
  font-weight: 600;
  margin: 0;
  color: #ffffff;
}

.system-status {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.dashboard-content {
  flex: 1;
  display: flex;
  width: 100%;
  overflow: hidden;
}

/* 左侧会话列表 */
.conversation-sidebar {
  width: 320px;
  flex-shrink: 0;
  border-right: 1px solid #404040;
  overflow: hidden;
}

/* 右侧聊天区域 - 优化为增量加载容器 */
.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 欢迎区域 */
.welcome-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
}

.welcome-section h2 {
  font-size: 1.5rem;
  margin-bottom: 1rem;
  color: #ffffff;
}

.welcome-text {
  font-size: 1.1rem;
  color: #b0b0b0;
  max-width: 500px;
  margin: 0 auto 2rem auto;
  line-height: 1.6;
}

.welcome-button {
  margin-top: 1rem;
}

/* 错误通知 - 优化样式和位置 */
.error-notice {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  max-width: 600px;
  z-index: 1000;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .conversation-sidebar {
    width: 280px;
  }
}

@media (max-width: 480px) {
  .dashboard-content {
    flex-direction: column;
  }
  
  .conversation-sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #404040;
  }
}
</style>